プログラミング言語を作る準備運動 @moeki
moeki.icon
Peggy – Parser Generator for JavaScript
このパーサージェネレータがなんかシンプルそう
PEGという文法の実装なのか。
parslet - About
Rubyのライブラリもあるな...
なんかブラウザでインタプリタが動いたら楽しそうなのでPeggyにする
code:javascript
// Simple Arithmetics Grammar
// ==========================
//
// Accepts expressions like "2 * (3 + 4)" and computes their value.
Expression
= head:Term tail:(_ ("+" / "-") _ Term)* {
return tail.reduce(function(result, element) {
if (element1 === "+") { return result + element3; }
if (element1 === "-") { return result - element3; }
}, head);
}
ExpressionとかTermが rule の名前らしい。head とか tail が分からんな。
claude.iconによると優先度が高いルールを先に定義するらしい
_は空白
* は0回以上の繰り返し。正規表現と一緒だ
あーそうか、headがTermでtailは_ ("+" / "-") _ Termの0回以上の繰り返しか。そして element にはtailの文字列がくるんだ。
code:javascript
Term
= head:Factor tail:(_ ("*" / "/") _ Factor)* {
return tail.reduce(function(result, element) {
if (element1 === "*") { return result * element3; }
if (element1 === "/") { return result / element3; }
}, head);
}
Factor
= "(" _ expr:Expression _ ")" { return expr; }
/ Integer
/ Integer とは。。。
FactorにマッチしなかったらIntegerを試すという意味らしい
code:javascript
Integer "integer"
= _ 0-9+ { return parseInt(text(), 10); }
これは分かる。もらったテキストを10進数にしてる。text() っていうのが突然現れるのがなんかキモいが...
code:javascript
_ "whitespace"
= \t\n\r*
whitespaceは何と無く分かる。これらの文字列が空白を意味するよってことだ
code:javascript
Start
= Statement+
Statement
= Assignment
/ Expression
これで式を定義できる
Statementの1つ以上の繰り返し
code:code
hoge = 1
fuga = 1
これすらもエラーになる。 Line 2, column 1: Expected [*/], [+\-], or whitespace but "f" found.
EOSの定義が必要
code:code
EOS "end of statement"
= _ ";"
/ _ "\n"
/ _ EOF
これで hoge = 1;fuga = 1はパースされるようになった。なぜか\nがだめみたい。
あー_が余計だな。でも_ ;の方は必要っぽい?
とりあえずこんなん
code:code
EOS
= _ ";" "\n"*
/ "\n"
/ _ EOF
標準出力をつける
code:code
hoge = 1
$ hoge
意地でも予約語に英語を使わない
大体わかったので文法を考えていく。
関数リテラルが大好きなのでそれを主にしよう。UI向けの言語にしたいのでそんな雰囲気で